import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
const whiteList = ['/login', '/register'] // 不重定向白名单
NProgress.configure({ showSpinner: true })// NProgress Configuration
router.beforeEach((to, from, next) => {   //路由钩子
    NProgress.start()
    if (store.getters.token) {
        if (to.path === '/login') {
            next({path: '/home/index'})
        } else {
            if (store.getters.roles.length === 0) {
                store.dispatch('GetInfo').then(res => { // 拉取用户信息
                    let roles = res.role;
                    let permissionsList = res.permissionsList;
                    if (roles.length > 0 && permissionsList.length > 0) {
                        store.dispatch('GenerateRoutes', {roles:roles,permissionsList:permissionsList}).then(() => { //
                            router.addRoutes(store.getters.addRouters); //
                            router.addRoutes([{ path: '*', redirect: '/404', hidden: true }]);
                            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                        })

                    } else {
                        store.dispatch('FedLogOut').then(() => {
                            Message.error('没有分配菜单,请联系管理员分配菜单')
                            next({path: '/login'})
                        })
                    }
                }).catch(() => {
                    store.dispatch('FedLogOut').then(() => {
                        Message.error('验证失败,请重新登录')
                        next({path: '/login'})
                    })
                })
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done() // 结束Progress
})
